const HTTP_PRE = "http://119.23.185.69:7002";
// const HTTP_PRE = "http://localhost:7002";
var hasShow = false;
(function() {
	//加载用户
	initUser();
	//添加事件
	addEvents();
})();


function initUser(){
	let u = mainInfo();
	$("#name").html(u.name);
	//显隐操作按钮
    //1.用户是否登录
    if(u.isLogin){
        let runData = runDataInfo();
        if(runData.isRun){
            showHandel(3);//显示正在运行动画
        }else{
            showHandel(1);//显示同步按钮
        }
    }else{
        showHandel(2);//提示登录
    }
    //2.是否正在运行
	showHandel(u.isLogin?1:2);
}

function addEvents(){
 	//同步按钮
 	$("#dataBtn").on("click",function(){
 	    let runData = runDataInfo();
 	    if(!runData.isRun){
            //显示进度条
            showHandel(3);
            synchronizeData(false);
        }
 	});
 	//本地覆盖云端按钮
    $("#forceData").on("click",function(){
        let runData = runDataInfo();
        if(!runData.isRun){
            buttonNotice("此操作会使用本地的书签覆盖云端书签,彼时云端的书签和本地一模一样,云端所有历史书签将会丢失..."
                ,function (notificationId) {
                    //显示进度条
                    showHandel(3);
                    synchronizeData(true);
                    chrome.notifications.clear(notificationId,null);
                },function (notificationId) {
                    chrome.notifications.clear(notificationId,null);
            });


        }
    });

 	//切换用户按钮
 	$("#transUserBtn").on("click",function(){
 		send("setInfo",{
 		    "name":"fenmirs",
            "id":1
        },function () {
            initUser();
        });
 	});
}

function showHandel(flag){
	if(flag==1){
        $("#loading").hide();
		$("#div1").hide();
		$("#div2").show();
		$("#userDiv").show();
	}else if(flag==2){
		$("#loading").hide();
        $("#div1").show();
		$("#div2").hide();
        $("#userDiv").show();
	}else{
        $("#loading").show();
        $("#div1").hide();
        $("#div2").hide();
        $("#userDiv").hide();
    }
}


/**
 * 同步书签
 */
function synchronizeData(isForce) {
    //获取本地的所有书签并把树组装为List
    chrome.bookmarks.getTree(function(array){
        let upList = [];
        for(let index in array){
            treeToList(array[index],upList);
        }
        //提交至服务器
        $.ajax({
            url:HTTP_PRE+"/synchronizeData",
            data:JSON.stringify({
                "userId":mainInfo().id,
                "addOrOver":1,
                "list":upList,
                "isForce":isForce
            }),
            type:"POST",
            contentType:"application/json;charset=UTF-8",
            dataType:"json",
            timeout:1000*10,
            success:function(result,status,xhr){
                send("setRunData",{
                    "runCount":3,
                    "synchronizeCount":result.count,
                    "treeData":result['tree']
                },function () {
                    renderData();
                });
            },
            error:function (result) {
                showHandel(1);
                notice("由于超时等未知原因书签同步失败!");
            }
        });
    });
}
/**
 * 渲染树形数据
 * @param data
 */
function renderData() {
    hasShow = false;
    let runData = runDataInfo();
    if(runData.synchronizeCount>0){
        chrome.bookmarks.getChildren("1",function (array) {
            let count1 = array.length;
            let parentId = "1";
            if(count1>0){
                for(let i in array){
                    (function(index){
                        chrome.bookmarks.removeTree(array[index]["id"],function () {
                            count1--;
                            if(count1<=0){
                                childrenCreate({
                                    obj:runData["treeData"][0],
                                    parentId:parentId
                                });
                            }
                        });
                    })(i);
                }
            }else{
                childrenCreate({
                    obj:runData["treeData"][0],
                    parentId:parentId
                });
            }
        });
        chrome.bookmarks.getChildren("2",function (array) {
            let parentId = "2";
            let count2 = array.length;
            if(count2>0){
                for(let i in array){
                    (function(index){
                        chrome.bookmarks.removeTree(array[index]["id"],function () {
                            count2--;
                            if(count2<=0){
                                childrenCreate({
                                    obj:runData["treeData"][1],
                                    parentId:parentId
                                });
                            }
                        });
                    })(i);
                }
            }else{
                childrenCreate({
                    obj:runData["treeData"][1],
                    parentId:parentId
                });
            }
        });
    }else{
        showHandel(1);
        notice("没有同步到任何书签,你确定你有保存过任何书签吗?...");
    }
}
//子节点创建
function childrenCreate(param){
    let obj = param["obj"];
    let parentId = param["parentId"];

    for(let i in obj["children"]){
        let item  = obj["children"][i];
        chrome.bookmarks.create({
            "parentId":parentId,
            "index":item["bookmarkIndex"],
            "title":item["bookmarkName"],
            "url":item["bookmarkUrl"]
        }, function (ret2) {//生成节点后会自动产生id
            //计数,在同步完成后显示提示
            send("growRunCount",null,function () {
                let runData = runDataInfo();
                if(!runData.isRun&&!hasShow){
                    hasShow = true;
                    //显示控制按钮
                    showHandel(1);
                    notice("本次共同步 "+runData.synchronizeCount+" 个书签.");
                }
            });

            //子节点
            childrenCreate({
                obj:item,
                parentId:ret2["id"]
            });
        });
    }
}

function treeToList(obj,list){
    list.push({
        "bookmarksId":obj["id"],
        "bookmarkName":obj["title"],
        "bookmarkUrl":obj["url"],
        "parentDirId":obj["parentId"],
        "bookmarkIndex":obj["index"],
        "userId":mainInfo().id,
        "createTime":timeToInt(obj["dateAdded"])
    });

	//子节点处理
    let children = obj['children'];
	if(Object.prototype.toString.call(children) === '[object Array]'){
        for(let index in children){
            treeToList(children[index],list)
        }
    }
}
function timeToInt(time) {
    if(time){
        return (time+"").substr(0,time.length-3);
    }else{
        return 0;
    }
}



//--------------------------------------------------//
//给background.js发消息
function send(method, param, callBack){
    chrome.runtime.sendMessage({method:method, param:param}, callBack);
}

//获取background.js中的值
function mainInfo(){
	return chrome.extension.getBackgroundPage().Main.getInfo();
}
function runDataInfo(){
    return chrome.extension.getBackgroundPage().Main.getRunData();
}

//windos 系统级提示
function notice(msg) {
    chrome.notifications.create(null, {
        type: 'basic',
        iconUrl: 'images/logo.png',
        title: 'fenmirs bookmarks',
        message: msg
    });
}
function buttonNotice(msg,callBack1,callBack2) {
    chrome.notifications.create(null, {
        type: 'basic',
        iconUrl: 'images/logo.png',
        title: 'fenmirs bookmarks',
        message: msg,
        // contextMessage: msg,
        buttons: [{title:'确定',iconUrl:'images/ok.png'},{title:'取消',iconUrl:'images/cancel.png'}]
    });
    chrome.notifications.onButtonClicked.addListener(function(notificationId, buttonIndex) {
        if(buttonIndex==0){
            callBack1(notificationId)
        }else{
            callBack2(notificationId)
        }
    });
}